package com.finiac.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


import com.finiac.dao.UserDAO;
import com.finiac.exception.ChangePasswordException;
import com.finiac.exception.LoginException;
import com.finiac.exception.UnableToRegisterException;
import com.finiac.model.User;

public class AuthController extends MultiActionController {

	private String passwordHashPadding;
	private String userNameHashPadding;
	UserDAO userDAO;
	
	

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

	public AuthController() {
		this.passwordHashPadding="Change isn't always for the best ― Nicholas Sparks";
		this.userNameHashPadding="Truth only means something when it's hard to admit. - Nicholas Sparks, The Last Song ";
	}
	
	public boolean userLogin(HttpServletRequest request, String userName, String password)throws Exception
	{
		if(userName==null || password == null)
			throw new LoginException();
		String cryptPassword = DigestUtils.sha256Hex(password +passwordHashPadding);
		User user = new User();
		List<User> userList=userDAO.selectUser(userName,cryptPassword);
		if(userList.size()==0)
			throw new LoginException();
		for(int i=0;i<userList.size();i++)
		{
			user = userList.get(i);
		}
		request.getSession().setAttribute("userName", user.getUserName());
		request.getSession().setAttribute("userRole", user.getRole());
		return true;
	}
	
	public int userRegister(String userName, String password, String role) throws Exception
	{
		if(userName.length()<6||password.length()<6||role.length()==0)
			throw new UnableToRegisterException();
		String cryptPassword = DigestUtils.sha256Hex(password +passwordHashPadding);
		User user = new User();
		user.setUserName(userName);
		user.setPassword(cryptPassword);
		user.setRole(role);
		userDAO.addOrupdateUser(user);
		return 1;
	}
	
	private void changePassword(User user, String currentPassword, String newPassword1, String newPassword2) throws Exception
	{
		String cryptCurPassword = DigestUtils.sha256Hex(currentPassword +passwordHashPadding);
		if(!user.getPassword().equals(cryptCurPassword))
			throw new ChangePasswordException();
		if(!newPassword1.equals(newPassword2))
			throw new ChangePasswordException();
		if(newPassword1.length()<6)
			throw new ChangePasswordException();
		String cryptNewPassword = DigestUtils.sha256Hex(newPassword1 +passwordHashPadding);
		user.setPassword(cryptNewPassword);
		userDAO.updateUser(user);
	}
	
	public ModelAndView loginPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		request.getSession().removeAttribute("userName");
		request.getSession().removeAttribute("userRole");
		return new ModelAndView("login");
	}
	public void login(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		try{
			String userName= request.getParameter("userName");
			String password= request.getParameter("password");
			this.userLogin(request, userName, password);
			response.sendRedirect("../index.html");
		}catch (LoginException e) {
			response.sendRedirect("../auth/loginPage.htm?attempt=1");
		}
		
	}
	public ModelAndView addUserPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		ModelMap modelMap = new ModelMap();
		modelMap.addAttribute("userList", userDAO.listUser());
		modelMap.addAttribute("user", new User());
		return new ModelAndView("addUser",modelMap);
	}
	public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		try{
			String userName=request.getParameter("userName");
			String password=request.getParameter("password");
			String role=request.getParameter("role");
			if(!role.equals("ADMIN") && !role.equals("USER") && !role.equals("FEE"))
				throw new UnableToRegisterException();
			this.userRegister(userName, password, role);
			return new ModelAndView("redirect:addUserPage.htm");
			
		}
		catch (NullPointerException e) {
			return new ModelAndView("redirect:addUserPage.htm?nullValue=true");

		}
		catch (UnableToRegisterException e) {
			return new ModelAndView("redirect:addUserPage.htm?passwordLength=fail");

		}
	}
	public ModelAndView updateUserPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long id=Long.parseLong(request.getParameter("id"));
		User user = new User();
		user=userDAO.selectById(id);
		return new ModelAndView("updateUser", "user", user);
	}

	public ModelAndView updateUser(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		try{
			long userId=Long.parseLong(request.getParameter("userId"));
			String password=request.getParameter("password");
			String role=request.getParameter("role");
			if(password.length()<6||role.length()==0)
				throw new UnableToRegisterException();
			User user= new User();
			user= userDAO.selectById(userId);
			String cryptPassword = DigestUtils.sha256Hex(password +passwordHashPadding);
			user.setPassword(cryptPassword);
			user.setRole(role);
			userDAO.updateUser(user);
			return new ModelAndView("redirect:addUserPage.htm");
	}
			catch (UnableToRegisterException e) {
				long userId=Long.parseLong(request.getParameter("userId"));
				return new ModelAndView("redirect:updateUserPage.htm?passwordLength=fail&id="+userId);

			}
		
	}
	public void deleteUser(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		long id=Long.parseLong(request.getParameter("id"));
		userDAO.deleteUser(id);
	}
	public ModelAndView changePasswordPage(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		return new ModelAndView("changePassword");
	}
	public ModelAndView changePassword(HttpServletRequest request, HttpServletResponse response)throws Exception
	{
		String urlSuffix="";
		try{
		
				String currentPassword=request.getParameter("currentPassword");
				String newPassword1=request.getParameter("newPassword1");
				String newPassword2=request.getParameter("newPassword2");
				String userName=request.getSession().getAttribute("userName").toString();
				User user=userDAO.selectByUserName(userName);
				if(!newPassword1.equals(newPassword2))
					urlSuffix="passwordMismatch=true";
				else if(newPassword1.length()<6)
					urlSuffix+="passwordLength=false";
				changePassword(user,currentPassword,newPassword1,newPassword2);
				urlSuffix+="success=true";
		}catch (Exception e) {
			urlSuffix+="someError=true";
		}
		return new ModelAndView("redirect:changePasswordPage.htm?"+urlSuffix);
	}


}

